package handlers

import (
	"encoding/json"
	"github.com/gin-gonic/gin"
	"net/http"
	"news-like/cache"
	"news-like/models"
	"news-like/pkg"
	"strconv"
	"time"
)

func UserLogin(c *gin.Context) {
	username := c.PostForm("username")
	password := c.PostForm("password")
	if username == "" || password == "" {
		c.JSON(http.StatusOK, gin.H{
			"code": 0,
			"msg":  "用户名和密码不能为空",
		})
		return
	}
	login_key := "redis_login_key" + username
	errcount, _ := cache.Rdb.Get(cache.Ctx, login_key).Int()
	if errcount > 3 {
		c.JSON(http.StatusOK, gin.H{
			"code": 0,
			"msg":  "密码错误3次",
		})
		return
	}
	var user models.User
	err := models.DB.Where("username=?", username).First(&user).Error
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 0,
			"msg":  "用户名不存在",
		})
		return
	}
	if user.Password != pkg.Md5Str(password) {
		cache.Rdb.Incr(cache.Ctx, login_key)
		if errcount == 2 {
			cache.Rdb.Set(cache.Ctx, login_key, 3, time.Hour*2)
			c.JSON(http.StatusOK, gin.H{
				"code": 0,
				"msg":  "密码错误三次,封禁2小时",
			})
			return
		}
		c.JSON(http.StatusOK, gin.H{
			"code": 0,
			"msg":  "密码错误",
		})
		return
	}
	token, _ := pkg.TokenHandler(strconv.Itoa(int(user.ID)))
	c.JSON(http.StatusOK, gin.H{
		"code":  200,
		"msg":   "登录成功",
		"token": token,
	})
}
func List(c *gin.Context) {
	page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
	size, _ := strconv.Atoi(c.DefaultQuery("size", "3"))
	offset := (page - 1) * size
	var news []models.News
	list_key := "list_page_" + strconv.Itoa(page)
	cachejson, _ := cache.Rdb.Get(cache.Ctx, list_key).Result()
	if cachejson == "" {
		models.DB.Offset(offset).Limit(size).Find(&news)
		jsonData, _ := json.Marshal(news)
		cache.Rdb.Set(cache.Ctx, list_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cachejson), &news)
	}
	var total int64
	models.DB.Model(&news).Count(&total)
	c.JSON(http.StatusOK, gin.H{
		"code":  0,
		"msg":   "查询成功",
		"data":  news,
		"total": total,
	})
}
func Detail(c *gin.Context) {
	id := c.Query("id")
	var user models.User
	detail_key := "detail_" + id
	cachejson, _ := cache.Rdb.Get(cache.Ctx, detail_key).Result()
	if cachejson == "" {
		models.DB.Where("id=?", id).First(&user)
		jsonData, _ := json.Marshal(user)
		cache.Rdb.Set(cache.Ctx, detail_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cachejson), &user)
	}
	c.JSON(http.StatusOK, gin.H{
		"code": 200,
		"msg":  "查询成功",
		"data": user,
	})
}
func Like(c *gin.Context) {
	userId, _ := strconv.Atoi(c.PostForm("user_id"))
	newsId, _ := strconv.Atoi(c.PostForm("news_id"))
	like := models.Like{
		UserId: userId,
		NewsId: newsId,
	}
	err := models.DB.Create(&like).Error
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 0,
			"msg":  "点赞失败",
		})
		return
	}
	var news models.News
	err = models.DB.First(&news, newsId).Error
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 0,
			"msg":  "没有找到该帖子",
		})
		return
	}
	news.LikeCount++
	err = models.DB.Save(&news).Error
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 0,
			"msg":  "点赞量更新失败",
		})
		return
	} else {
		c.JSON(http.StatusOK, gin.H{
			"code": 200,
			"msg":  "点赞成功",
			"data": news,
		})
	}
}
